<template>
  <div>
    <el-upload
      ref="uploadRef"
      class="upload-demo"
      :auto-upload="false"
      :http-request="submitUpload"
      :before-upload="beforeUpload"
    >
      <template #trigger>
        <el-button type="primary">选择文件</el-button>
      </template>

      <el-button class="ml-3" type="success" @click="sureUpload">
        上传远程
      </el-button>

      <template #tip>
        <div class="el-upload__tip">
          jpg/png files with a size less than 500kb
        </div>
      </template>
    </el-upload>
  </div>
</template>


<script>
import request from "utils/request";
import { ElMessage } from "element-plus";
export default {
  name: "NestExcel",

  data() {
    return {};
  },

  methods: {
    beforeUpload(file) {
      const allowedTypes = [
        "application/vnd.ms-excel",
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      ];
      const isAllowed = allowedTypes.includes(file.type);
      const isLt2M = file.size / 1024 / 1024 < 2; // 这里假设限制文件大小为2MB

      if (!isAllowed) {
        ElMessage.error("只能上传Excel文件！");
      } else if (!isLt2M) {
        ElMessage.error("上传的文件大小不能超过 2MB!");
      }

      return isAllowed && isLt2M;
    },
    async submitUpload(val) {
      const imgData = new FormData(); // 创建form对象
      imgData.append("file", val.file); // 通过append向form对象添加数据
      imgData.append("namespace", "excel");
      const config = {
        headers: { "Content-Type": "multipart/form-data" },
      };
      let ret = await request.upload("/excel/analyze", imgData, config);
      console.log("🚀 ~ importExcel ~ ret:", ret);
    },
    async sureUpload() {
      this.$refs["uploadRef"].submit();
    },
  },
};
</script>